<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { login } from '@/api/auth.js'
import { useThemeStore } from '@/stores/theme'
import ToggleTheme from '@/components/ToggleTheme.vue'
import PuzzleCode from "@/components/PuzzleCode.vue";

const router = useRouter()
const themeStore = useThemeStore()

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: '',
  slideVerify: false
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

// 加载状态
const loading = ref(false)

// 表单引用
const formRef = ref(null)

// 处理登录
const handleLogin = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      if (!loginForm.slideVerify) {
        ElMessage.warning('请完成滑块验证')
        return
      }
      loading.value = true
      try {
        const res = await login(loginForm)
        if (res.code === 200) {
          // 保存token到localStorage
          localStorage.setItem('token', res.data.token)
          localStorage.setItem('userInfo', JSON.stringify({
            id: res.data.id,
            username: res.data.username,
            email: res.data.email
          }))

          ElMessage.success('登录成功')

          // 延迟一小段时间确保token生效后再跳转
          setTimeout(() => {
            router.push('/')
          }, 100)
        } else {
          ElMessage.error(res.msg || '登录失败')
        }
      } catch (error) {
        console.error('登录出错:', error)
        ElMessage.error('登录失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }
  })
}

// 滑块验证成功回调
const handleSlideSuccess = (x) => {
  loginForm.slideVerify = true
  ElMessage.success('验证成功')
}

// 滑块验证失败回调
const handleSlideFail = (x) => {
  loginForm.slideVerify = false
  ElMessage.warning('验证失败，请重试')
}

// 跳转到注册页
const goToRegister = () => {
  router.push('/register')
}
</script>

<template>
  <div class="login-container" :class="{ 'dark-theme': themeStore.isDark }">
    <!-- 背景装饰 -->
    <div class="background-decoration">
      <div class="floating-shape shape-1"></div>
      <div class="floating-shape shape-2"></div>
      <div class="floating-shape shape-3"></div>
      <div class="floating-shape shape-4"></div>
    </div>

    <!-- 主题切换按钮 -->
    <div class="theme-toggle-wrapper">
      <ToggleTheme />
    </div>

    <div class="login-box">
      <div class="login-header">
        <div class="logo-section">
          <div class="logo-icon">
            <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M12 2L2 7L12 12L22 7L12 2Z" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/>
              <path d="M2 17L12 22L22 17" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/>
              <path d="M2 12L12 17L22 12" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/>
            </svg>
          </div>
          <h2>AI角色扮演</h2>
        </div>
        <p>欢迎回来，请登录您的账号</p>
      </div>

      <el-form
        ref="formRef"
        :model="loginForm"
        :rules="rules"
        label-position="top"
        class="login-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="User"
            class="glass-input"
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
            class="glass-input"
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        <!-- 滑块验证码 -->
        <el-form-item label="验证码" prop="slideVerify">
          <PuzzleCode
              v-model:complete="loginForm.slideVerify"
              :canvas-width="300"
              :canvas-height="160"
              :slider-size="40"
              :border-radius="8"
              success-text="验证成功！"
              fail-text="验证失败，请重试"
              slider-text="请拖动滑块完成验证"
              @success="handleSlideSuccess"
              @fail="handleSlideFail"
          />
        </el-form-item>
        <el-button
          type="primary"
          :loading="loading"
          class="login-button glass-button"
          @click="handleLogin"
        >
          <span v-if="!loading">登录</span>
          <span v-else>登录中...</span>
        </el-button>
      </el-form>

      <div class="login-footer">
        <p>还没有账号？<el-link type="primary" @click="goToRegister">立即注册</el-link></p>
      </div>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  overflow: hidden;
  transition: all 0.3s ease;
}

/* 暗黑主题 */
.login-container.dark-theme {
  background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
}

/* 背景装饰 */
.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  overflow: hidden;
}

.floating-shape {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  animation: float 6s ease-in-out infinite;
}

.shape-1 {
  width: 80px;
  height: 80px;
  top: 10%;
  left: 10%;
  animation-delay: 0s;
}

.shape-2 {
  width: 120px;
  height: 120px;
  top: 20%;
  right: 15%;
  animation-delay: 2s;
}

.shape-3 {
  width: 60px;
  height: 60px;
  bottom: 20%;
  left: 20%;
  animation-delay: 4s;
}

.shape-4 {
  width: 100px;
  height: 100px;
  bottom: 10%;
  right: 10%;
  animation-delay: 1s;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(-20px) rotate(180deg);
  }
}

/* 主题切换按钮 */
.theme-toggle-wrapper {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 10;
}

/* 登录框 */
.login-box {
  width: 420px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  border-radius: 20px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 25px 45px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.dark-theme .login-box {
  background: rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.1);
  box-shadow: 0 25px 45px rgba(0, 0, 0, 0.3);
}

.login-box:hover {
  transform: translateY(-5px);
  box-shadow: 0 35px 55px rgba(0, 0, 0, 0.15);
}

/* 登录头部 */
.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.logo-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 15px;
}

.logo-icon {
  width: 60px;
  height: 60px;
  margin-bottom: 15px;
  color: rgba(255, 255, 255, 0.9);
  background: rgba(255, 255, 255, 0.1);
  border-radius: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}

.logo-icon:hover {
  transform: scale(1.1);
  background: rgba(255, 255, 255, 0.2);
}

.logo-icon svg {
  width: 30px;
  height: 30px;
}

.login-header h2 {
  font-size: 28px;
  color: rgba(255, 255, 255, 0.95);
  margin: 0;
  font-weight: 600;
  letter-spacing: 1px;
}

.login-header p {
  font-size: 16px;
  color: rgba(255, 255, 255, 0.7);
  margin: 0;
  font-weight: 300;
}

/* 表单样式 */
.login-form {
  margin-top: 20px;
}

.login-form :deep(.el-form-item__label) {
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
  font-size: 14px;
}

.glass-input {
  transition: all 0.3s ease;
}

.glass-input :deep(.el-input__wrapper) {
  background: rgba(255, 255, 255, 0.08);
  backdrop-filter: blur(15px);
  border: 1px solid rgba(255, 255, 255, 0.15);
  border-radius: 12px;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.glass-input :deep(.el-input__wrapper:hover) {
  background: rgba(255, 255, 255, 0.12);
  border-color: rgba(255, 255, 255, 0.25);
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1), 0 4px 12px rgba(255, 255, 255, 0.1);
}

.glass-input :deep(.el-input__wrapper.is-focus) {
  background: rgba(255, 255, 255, 0.15);
  border-color: rgba(64, 158, 255, 0.5);
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1), 0 0 0 3px rgba(64, 158, 255, 0.15), 0 8px 25px rgba(64, 158, 255, 0.2);
}

.glass-input :deep(.el-input__inner) {
  color: rgba(255, 255, 255, 0.95);
  background: transparent;
  font-weight: 400;
}

.glass-input :deep(.el-input__inner::placeholder) {
  color: rgba(255, 255, 255, 0.45);
  font-weight: 300;
}

.glass-input :deep(.el-input__prefix-inner),
.glass-input :deep(.el-input__suffix-inner) {
  color: rgba(255, 255, 255, 0.55);
  transition: color 0.3s ease;
}

.glass-input:hover :deep(.el-input__prefix-inner),
.glass-input:hover :deep(.el-input__suffix-inner) {
  color: rgba(255, 255, 255, 0.75);
}

/* 表单操作区域 */
.form-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
}

.remember-checkbox :deep(.el-checkbox__label) {
  color: rgba(255, 255, 255, 0.8);
  font-size: 14px;
}

.remember-checkbox :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: rgba(64, 158, 255, 0.8);
  border-color: rgba(64, 158, 255, 0.8);
}

.forgot-link {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}

.forgot-link:hover {
  color: rgba(64, 158, 255, 0.9);
}

/* 登录按钮 */
.glass-button {
  width: 100%;
  height: 50px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 12px;
  background: rgba(64, 158, 255, 0.8);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: white;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.glass-button::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.glass-button:hover::before {
  left: 100%;
}

.glass-button:hover {
  background: rgba(64, 158, 255, 0.9);
  transform: translateY(-2px);
  box-shadow: 0 10px 25px rgba(64, 158, 255, 0.3);
}

.glass-button:active {
  transform: translateY(0);
}

/* 登录底部 */
.login-footer {
  text-align: center;
  margin-top: 25px;
  padding-top: 20px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.login-footer p {
  color: rgba(255, 255, 255, 0.7);
  font-size: 14px;
  margin: 0;
}

.login-footer .el-link {
  color: rgba(64, 158, 255, 0.9);
  font-weight: 500;
}

/* 暗黑主题下的特殊样式 */
.dark-theme .login-header h2 {
  color: rgba(255, 255, 255, 0.95);
}

.dark-theme .login-header p {
  color: rgba(255, 255, 255, 0.6);
}

.dark-theme .glass-input :deep(.el-input__wrapper) {
  background: rgba(0, 0, 0, 0.15);
  border-color: rgba(255, 255, 255, 0.08);
  box-shadow: inset 0 1px 3px rgba(255, 255, 255, 0.05);
}

.dark-theme .glass-input :deep(.el-input__wrapper:hover) {
  background: rgba(0, 0, 0, 0.25);
  border-color: rgba(255, 255, 255, 0.15);
  box-shadow: inset 0 1px 3px rgba(255, 255, 255, 0.05), 0 4px 12px rgba(0, 0, 0, 0.2);
}

.dark-theme .glass-input :deep(.el-input__wrapper.is-focus) {
  background: rgba(0, 0, 0, 0.3);
  border-color: rgba(64, 158, 255, 0.6);
  box-shadow: inset 0 1px 3px rgba(255, 255, 255, 0.05), 0 0 0 3px rgba(64, 158, 255, 0.2), 0 8px 25px rgba(64, 158, 255, 0.3);
}

.dark-theme .glass-input :deep(.el-input__inner::placeholder) {
  color: rgba(255, 255, 255, 0.35);
}

.dark-theme .glass-input :deep(.el-input__prefix-inner),
.dark-theme .glass-input :deep(.el-input__suffix-inner) {
  color: rgba(255, 255, 255, 0.45);
}

.dark-theme .glass-input:hover :deep(.el-input__prefix-inner),
.dark-theme .glass-input:hover :deep(.el-input__suffix-inner) {
  color: rgba(255, 255, 255, 0.65);
}

.dark-theme .floating-shape {
  background: rgba(255, 255, 255, 0.05);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-box {
    width: 90%;
    max-width: 380px;
    padding: 30px 25px;
    margin: 20px;
  }

  .theme-toggle-wrapper {
    top: 15px;
    right: 15px;
  }

  .floating-shape {
    display: none;
  }
}

@media (max-width: 480px) {
  .login-header h2 {
    font-size: 24px;
  }

  .login-box {
    padding: 25px 20px;
  }
}
</style>
